// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.services;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import lichen.entities.forum.Forum;
import lichen.entities.forum.ForumImpl;
import lichen.entities.post.Topic;
import lichen.services.Menu;
import lichen.services.MenuService;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author jcai
 * @version $Revision: 59 $
 * @since 0.0.2
 */
@Transactional
public class MenuServiceImpl implements MenuService {
	private HibernateTemplate _template;
	private static final String QUERY_PARENT_FORUMS_HQL = "from "+ForumImpl.class.getName()+
	" f where f."+ForumImpl.LEFT_PRO_NAME+"<? and f."+ForumImpl.RIGHT_PRO_NAME+">? order by f."+ForumImpl.LEFT_PRO_NAME;
	public MenuServiceImpl(HibernateTemplate template){
		_template = template;
	}
	/**
	 * @see lichen.services.MenuService#generateForumMenu(lichen.entities.forum.Forum)
	 */
	public  List<Menu> generateForumMenu(Forum forum) {
		List<Menu> menus = generateParentForumMenu(forum);
		//TODO 目前Tapestry的pagelink还不支持disable参数，故加上所有的链接
		ForumMenu menu=  new ForumMenu(forum,true);
		menus.add(menu);
		return menus;
	}
	private List<Menu> generateParentForumMenu(Forum forum){
		Iterator it = _template.iterate(QUERY_PARENT_FORUMS_HQL, new Object[]{forum.getLeft(),forum.getRight()});
		
		List<Menu> menus = new ArrayList<Menu>();
		while(it.hasNext()){
			ForumMenu menu=  new ForumMenu((Forum) it.next(),false);
			menus.add(menu);
		}
		return menus;
	}

	/**
	 * @see lichen.services.MenuService#generateForumMenu(lichen.entities.forum.Forum, lichen.entities.post.Topic)
	 */
	public  List<Menu> generateForumMenu(Forum forum, Topic topic) {
		List<Menu> menus = generateParentForumMenu(forum);
		Menu menu=  new ForumMenu(forum,false);
		menus.add(menu);
		
		if(topic!=null&&topic.getId() != null){
			TopicMenu topicMenu = new TopicMenu(topic,false);
			menus.add(topicMenu);
		}
		return menus;
	}
}
